<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import CustomNavbar from './components/CustomNavbar.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from './components/PageSkeleton.vue'
import { useGuessList } from '@/composables'
// 轮播图列表
const bannerList = ref<BannerItem[]>([])
// 分类列表
const categoryList = ref<CategoryItem[]>([])
// 热门数据列表
const hotList = ref<HotItem[]>([])

const getBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
const getCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

const getHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
// 使用hooks
const { guessRef, onScrollToLower } = useGuessList()

// 是否开启下拉刷新动画
const isTriggered = ref(false)
// 下拉刷新事件
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 开启同步执行
  // await getBannerData()
  // await getCategoryData()
  // await getHotData()
  // 先重置分页器数据
  guessRef.value?.resetData()
  await Promise.all([getBannerData(), getCategoryData(), getHotData(), guessRef.value?.getMore()])
  // 关闭动画
  isTriggered.value = false
}

const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerData(), getCategoryData(), getHotData()])
  isLoading.value = false
})
</script>

<template>
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    scroll-y
    @scrolltolower="onScrollToLower"
    class="scroll-view"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <XtxSwiper :list="bannerList" />
      <CategoryPanel :list="categoryList" />
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  display: flex;
  height: 100%;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
  overflow: auto;
}
</style>
